package sunwin.yoms.service.person;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import jodd.datetime.JDateTime;
import jodd.util.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sunwin.yoms.comm.FileHelper;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsPage;
import sunwin.yoms.dao.UserDao;
import sunwin.yoms.domain.person.UserDomain;
import sunwin.yoms.service.comm.YomsDefaultData;
import sunwin.yoms.service.security.YomsUserDetails;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by mt on 2015/7/26.
 */
@Service
@SuppressWarnings("unchecked")
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 保存用户头像
     *
     * @param file
     * @return
     * @throws YomsException
     */
    public String saveUserAvatar(MultipartFile file, YomsUserDetails userDetails) throws YomsException {
        String fileName = null;
        String fileDir = null;

        if (!file.isEmpty()) {
            fileName = userDetails.getUsername() + "." + FileHelper.getExtensionName(file.getOriginalFilename());
            fileDir = new File(YomsDefaultData.WebRoot, "img/avatar").getAbsolutePath();
            try {
                file.transferTo(new File(fileDir, fileName));
                userDetails.setAvatar(fileName);
            } catch (IOException e) {
                fileName = null;
                throw new YomsException("保存用户头像失败");
            }
        }
        return fileName;
    }

    /**
     * 获取个人资料最新信息
     */
    public UserDomain getAdmin(YomsUserDetails userDetails) throws YomsException {
        UserDomain domain = this.getUserById(userDetails.getUserid());
        return domain;
    }

    /**
     * 修改个人密码
     *
     * @param id
     * @throws YomsException
     */
    public void changePassword(int id, String oldPsd, String newPsd) throws YomsException {
        UserDomain domain = this.getUserById(id);
        String str = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";   //必须同时包含字母数字并且是6-20位
        if (newPsd.matches(str)) {
            if (BCrypt.checkpw(oldPsd, domain.getUserLoginPassword())) {
                domain.setUserLoginPassword(BCrypt.hashpw(newPsd, BCrypt.gensalt()));
                if (this.userDao.updateDomain(domain) == 1) {
                    this.userDao.updateDomain(domain);
                } else {
                    throw YomsException.getInstance("修改密码失败");
                }
            } else {
                throw YomsException.getInstance("输入的原密码不匹配");
            }
        } else {
            throw new YomsException("密码必须同时包含字母数字");
        }

    }

    /**
     * 查找用户
     *
     * @param userDomain
     * @param yomsPage
     * @param startTime
     * @param endTime
     * @return
     * @throws YomsException
     */
    public List<UserDomain> findUser(UserDomain userDomain, YomsPage yomsPage, Date startTime, Date endTime) throws YomsException {
        long total = 0;
        long pageSize = yomsPage.getPageSize();

        Page page = PageHelper.startPage(yomsPage.getPageIndex(), yomsPage.getPageSize(), true);

        List<UserDomain> userDomains = userDao.getDomainCollectionExtend(userDomain, startTime, endTime);

        removeAdmin(userDomains);

        total = page.getTotal() - 1;

        yomsPage.setPageCount(total % pageSize == 0 ? total / pageSize : total / pageSize + 1);

        if (userDomains.size() == 0) {
            throw new YomsException("没有找到用户", 1);
        }

        return userDomains;
    }

    /**
     * 删除用户
     *
     * @param id
     * @throws YomsException
     */
    public void delUser(int id) throws YomsException {
        UserDomain userDomain = new UserDomain();
        userDomain.setUserId(id);

        UserDomain domain = userDao.getDomainById(userDomain.getUserId());
        if (domain == null) {
            throw new YomsException("没有找到指定的用户");
        } else {
            if (domain.getUserLoginName().equals(YomsDefaultData.AdminLoginName)) {
                throw new YomsException("该用户不允许删除");
            } else {
                if (userDao.deleteDomain(userDomain) != 1) {
                    throw new YomsException("删除用户失败");
                }
            }
        }
    }

    /**
     * 修改密码
     *
     * @param userDomain
     * @throws YomsException
     */
    public void updateUser(UserDomain userDomain) throws YomsException {
        userDomain.setUserLoginName(null);
        userDomain.setUserCreateTime(null);
        userDomain.setUserLoginPassword(null);

        UserDomain domain = userDao.getDomainById(userDomain.getUserId());
        if (domain == null) {
            throw new YomsException("没有找到指定的用户");
        } else {
            if (userDao.updateDomain(userDomain) != 1) {
                throw new YomsException("修改用户失败");
            }
        }
    }

    /**
     * 创建用户
     *
     * @param userDomain
     * @throws YomsException
     */
    public void createUser(UserDomain userDomain) throws YomsException {
        if (userDomain.getUserLoginName().equals("default.admin") ||
                userDomain.getUserLoginName().equals(YomsDefaultData.AdminLoginName)) {
            throw new YomsException("创建用户失败，该用户名已被占用", 2);
        }
        userDomain.setUserCreateTime(new JDateTime(System.currentTimeMillis()).convertToDate());
        userDomain.setUserLoginPassword(BCrypt.hashpw("123456", BCrypt.gensalt()));

        UserDomain user = new UserDomain();
        user.setUserLoginName(userDomain.getUserLoginName());
        List<UserDomain> users = userDao.getDomainByCondition(user);
        if (users.size() > 0) {
            throw new YomsException("创建用户失败，该用户名已被占用", 2);
        }

        if (userDao.addDomain(userDomain) != 1) {
            throw new YomsException("创建用户失败");
        }
    }

    /**
     * 查询用户名是否存在
     */
    public List<UserDomain> queryUserName(String userLoginName) {
        UserDomain Domain = new UserDomain();
        Domain.setUserLoginName(userLoginName);
        List<UserDomain> userDomain1 = userDao.getDomainCollection(Domain);
        return userDomain1;
    }


    /**
     * 注册用户
     */
    public void register(UserDomain userDomain) throws YomsException {
        userDomain.setUserCreateTime(new JDateTime(System.currentTimeMillis()).convertToDate());

        userDomain.setUserLevelId(1);
        userDomain.setUserStateId(1);
        //支持中英文（包括全角字符）、数字、下划线和减号 （全角及汉字算两位）,长度为4-20位
        String str1 = "^[\\w\\-－＿[０-９]\u4e00-\u9fa5\uFF21-\uFF3A\uFF41-\uFF5A]{4,20}$";
        if (userDomain.getUserLoginName().matches(str1)) {
            userDomain.setUserLoginName(userDomain.getUserLoginName());
        } else {
            throw new YomsException("用户名不合法", 1);
        }
        if (userDao.addDomain(userDomain) != 1) {
            throw new YomsException("注册失败", 1);
        }
    }

    /**
     * 个人资料配置
     */
    public UserDomain personConfig1(int id, String nickName) throws YomsException {
        UserDomain dbDomain = userDao.getDomainById(id);
        if (dbDomain == null) {
            throw new YomsException("数据不存在", 1);
        } else {
            dbDomain.setUserNickname(nickName);
            if (userDao.updateDomain(dbDomain) != 1) {
                throw new YomsException("个人资料配置失败", 1);
            }
            return dbDomain;
        }
    }


    public void personConfig2(int id, String phoneNumber) throws YomsException {
        UserDomain dbDomain = userDao.getDomainById(id);
        UserDomain userDomainPhone = new UserDomain();
        userDomainPhone.setUserPhoneNumber(phoneNumber);
        List<UserDomain> domain1s = userDao.getDomainCollection(userDomainPhone);
        if (dbDomain == null) {
            throw new YomsException("数据不存在", 1);
        } else {
            if (domain1s.size() == 0) {
                dbDomain.setUserPhoneNumber(phoneNumber);
                if (userDao.updateDomain(dbDomain) != 1) {
                    throw new YomsException("个人资料配置失败", 1);
                }
            } else {
                throw new YomsException("该手机号已经被占用");
            }

        }
    }

    public void personConfig3(int id, String email) throws YomsException {
        UserDomain dbDomain = userDao.getDomainById(id);
        UserDomain userDomainEmail = new UserDomain();
        userDomainEmail.setUserEmail(email);
        List<UserDomain> domains2 = userDao.getDomainCollection(userDomainEmail);
        if (dbDomain == null) {
            throw new YomsException("数据不存在", 1);
        } else {
            if (domains2.size() == 0) {
                dbDomain.setUserEmail(email);
                if (userDao.updateDomain(dbDomain) != 1) {
                    throw new YomsException("个人资料配置失败", 1);
                }
            } else {
                throw new YomsException("该邮箱已经被占用");
            }
        }
    }


    /**
     * 根据用户ID获取用户
     *
     * @param id
     * @return
     * @throws YomsException
     */
    public UserDomain getUserById(int id) throws YomsException {
        UserDomain domain = userDao.getDomainById(id);
        if (domain == null) {
            throw new YomsException("无法找到指定用户", 1);
        }
        return domain;
    }

    /**
     * 根据管理员登录名获取后台管理员
     *
     * @param userLoginName
     * @return
     * @throws YomsException
     */
    public UserDomain getAdminByLoginName(String userLoginName) throws YomsException {
        UserDomain userDomain = new UserDomain();
        userDomain.setUserLoginName(userLoginName);
        userDomain.setUserLevelId(YomsDefaultData.AdminLevelId);
        List<UserDomain> userDomainList = userDao.getDomainByCondition(userDomain);
        if (userDomainList.size() == 1) {
            return userDomainList.get(0);
        } else {
            throw new YomsException("无法找到指定用户");
        }
    }

    /**
     * 根据用户登录名获取用户
     *
     * @param userLoginName
     * @return
     * @throws YomsException
     */
    public UserDomain getUserByLoginName(String userLoginName) throws YomsException {
        UserDomain userDomain = new UserDomain();
        userDomain.setUserLoginName(userLoginName);
        List<UserDomain> userDomainList = userDao.getDomainByCondition(userDomain);
        if (userDomainList.size() == 1) {
            return userDomainList.get(0);
        } else {
            throw new YomsException("无法找到指定用户");
        }
    }

    /**
     * 获取所有管理员. 不包含超级管理员
     *
     * @return
     */
    public List<UserDomain> getAdmins() {
        UserDomain userDomain = new UserDomain();
        userDomain.setUserLevelId(2);

        List<UserDomain> userDomains = userDao.getDomainCollection(userDomain);

        removeAdmin(userDomains);

        return userDomains;
    }

    /**
     * 根据角色value获取用户
     *
     * @param roleValue 角色value
     * @return
     */
    public List<UserDomain> getUserByRole(long roleValue) {
        List<UserDomain> userDomains = userDao.getUsersByRole(roleValue);
        removeAdmin(userDomains);
        return userDomains;
    }

    /**
     * 将超级管理员在显示列表中移除
     *
     * @param userDomains
     */
    private void removeAdmin(List<UserDomain> userDomains) {
        for (UserDomain domain : userDomains) {
            if (domain.getUserLoginName().equals(YomsDefaultData.AdminLoginName)) {
                userDomains.remove(domain);
                break;
            }
        }
    }
}